import AsyncStorage from '@react-native-async-storage/async-storage'

let cache: Record<string, any> = {}

export enum StorageKey {
  token = 'token',
  isNewUsers = 'isNewUsers',
  deviceMaintenance = 'deviceMaintenance',
  userId = 'userId',
  displayedPrivacyPolicy = 'displayedPrivacyPolicy',
  connectCount = 'connectCount'
}

export default class Storage {
  static get(key: StorageKey): Promise<any | null> {
    if (cache[key]) return cache[key]
    return AsyncStorage.getItem(key).then((value) => {
      if (!value) return value
      const jsonValue = JSON.parse(value)
      return jsonValue
    })
  }

  static set(key: StorageKey, value: any) {
    cache[key] = value
    return AsyncStorage.setItem(key, JSON.stringify(value))
  }

  static delete(key: StorageKey) {
    cache[key] = undefined
    return AsyncStorage.removeItem(key)
  }

  static clear() {
    cache = {}
    return AsyncStorage.clear()
  }
}
